import sys;
sys.path.append('..');
import ConfigParser, os;
from by.vaukalak.core.application.Application import *;
from by.vaukalak.core.net.socket.SocketServer import *;
from by.vaukalak.core.net.socket.SocketEvent import *;
from by.vaukalak.core.net.commands.CommandSerializer import *;
from core.BoardData import BoardData;
from core.PeacePosition import *;
from rules.RulesController import *;
from game.Player import Player;
from game.Game import Game;
from database.DataBase import DataBase;

class Kniazhych(Application):

    def __init__(self):
        Application.__init__(self);

    def onAppStart(self):

        print "start application";

        config = ConfigParser.ConfigParser();
        config.readfp(open('server.cfg'));
        port = int(config.get('Application Config', 'server_port'));

        self._openGame = None;
        self._dataBase = DataBase('127.0.0.1', 3306, 'root', 'nysht88', 'kniazhych');
        self._clients = {};
        self._games = {};
        self._attendingClient =list();
        self.server = SocketServer("localhost", port);
        self.server.addEventListener(SocketEvent.NEW_CONNECTION, self.handleNewConnection);
        self._serializer = CommandSerializer();

        print self._dataBase.getStatistics(0,0);

    def handleNewConnection(self, event):

        event.connection.addEventListener(SocketEvent.DATA_RECIVED, self.handleDataRecived);

    def handleDataRecived(self, event):
        command = self._serializer.deserialize(event.data);
        if(command.name == "connect"):
            if(command.params[0] in self._clients):
                event.connection.close();
            else:
                self._clients[command.params[0]] = event.connection;
                if(self._openGame == None):
                    print "create a new game";
                    self._openGame = Game(self._dataBase);
                    self._openGame.player1 = Player(event.connection, self._dataBase, command.params[2], command.params[0], 0);
                else:
                    print "start a new game";
                    self._openGame.player2 = Player(event.connection, self._dataBase, command.params[2], command.params[0], 1);

                    self._openGame.start();
                    self._games[self._openGame.id] = self._openGame;
                    self._openGame = None;
        elif(command.name == "getStatistics"):
            print self._dataBase.getStatistics(0,0);
        print "handleDataRecived executed";

#application starter
application = Kniazhych();